package com.yixia.framework.config;


import com.yixia.framework.security.JwtAuthenticationEntryPoint;
import com.yixia.framework.security.JwtAuthenticationFilter;
import com.yixia.framework.security.JwtLogoutSuccessHandler;
import com.yixia.framework.security.MyUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring security配置
 * @author: 依梦
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtLogoutSuccessHandler jwtLogoutSuccessHandler;
    @Autowired
    private MyUserDetailsServiceImpl myUserDetailsService;
    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;/*认证失败处理区*/

    private static final String[] URL_WHITELIST ={
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**",
            "/test/**",
            "/profile/**",
            "/swagger**/**",
            "/v3/**"
    } ;

    /*密码的加密*/
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter(authenticationManager());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启跨域 和 csrf攻击 关闭
        http
                .cors()
                .and()
                .csrf().disable()// CSRF禁用，因为不使用session


                // 登录登出配置
                /*.formLogin()*/
                /*.successHandler(loginSuccessHandler)*/
                /*.failureHandler(loginFailureHandler)*/
                /*.and()*/
                .logout()
                .logoutSuccessHandler(jwtLogoutSuccessHandler)

                // session禁用配置
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                // 拦截规则配置
                .and()

                // 过滤请求
                .authorizeRequests()
                // 对于这些接口 允许匿名访问
                .antMatchers(URL_WHITELIST).permitAll()
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**", "/doc.html").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()

                // 开启嵌套
                /**
                 * X-Frame-Options有以下配置项：
                 * 1.DENY：不能被嵌入到任何iframe或者frame中。
                 * 2.SAMEORIGIN：页面只能被本站页面嵌入到iframe或者frame中
                 * 3.ALLOW-FROM uri：只能被嵌入到指定域名的框架中。
                 */
                .headers().frameOptions().disable();

        // 异常处理器配置
        http.exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint);
        // 自定义过滤器配置
        /*http.addFilter(jwtAuthenticationFilter());*/
        //把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    /*获取AuthenticationManager*/
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.userDetailsService(myUserDetailsService).passwordEncoder(bCryptPasswordEncoder());*/
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    /**
     * 对configure的配置
     * @return
     */
    @Bean
    public AuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(myUserDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
        //将
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        return daoAuthenticationProvider;
    }
}